﻿using AiShua.CookiePool.Model;
using AiShua.CookiePool.Utils;
using Newtonsoft.Json.Linq;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AiShua.CookiePool.Task
{
    public class CheackAccount : IInterruptableJob
    {
        DB.DB db = new DB.DB();
        void IJob.Execute(IJobExecutionContext context)
        {
            string msg = "";
            List<T_Cookie> cookies = db.GetAllCookie(out msg);
            foreach (var item in cookies)
            {
                bool result = CheackCookie(item);
                if(!result)
                {
                    //移除Cookie
                    db.DeleteCookie(item.UserName);
                }
            }
        }

        public bool CheackCookie(T_Cookie Cookie)
        {
            int count = 1;
            HTTP:
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem();
            item.Url = "https://www.ximalaya.com/revision/main/getCurrentUser";
            item.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            item.Cookie = Cookie.Cookie;
            item.Referer = "https://www.ximalaya.com";
            item.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36";
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                JObject jobj = null;
                try
                {
                    jobj = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(result.Html);
                }
                catch (Exception ex)
                {
                    if (count == 3)
                    {
                        return false;
                    }
                    count++;
                    goto HTTP;
                }
                if (jobj["msg"].Value<string>() == "用户基本信息")
                {
                    return true;
                }
                else
                {
                    if (count == 3)
                    {
                        return false;
                    }
                    count++;
                    goto HTTP;
                }
            }
            else
            {
                goto HTTP;
            }
        }

        void IInterruptableJob.Interrupt()
        {

        }
    }
}